<template>
  <div class="app-container">
    <div style="margin-bottom: 20px;" class="clearfix">
      <el-input v-model="listQuery.menuName" placeholder="请输入菜单名称" style="width: 200px;" class="filter-item" clearable @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.systemType" placeholder="请选择权限所属系统" clearable class="filter-item" style="width: 160px">
        <el-option label="商户系统" value="1" />
        <el-option label="总后台" value="2" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 20px;" @click="handleFilter">
        搜索
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-plus" style="float:right" @click="handleAdd">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      row-key="id"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :element-loading-text="g.loadingStr"
      :header-cell-style="{background:g.mainColor}"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="序号" align="center" width="100" fixed>
        <template slot-scope="{$index}">
          <span>{{ $index + 1 + ( listQuery.currentPage - 1 ) * listQuery.pageSize }}</span>
        </template>
      </el-table-column>
      <el-table-column label="功能名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center">
        <template slot-scope="{row}">
          <span><img :src="row.icon" alt="" class="table-row-img"></span>
        </template>
      </el-table-column>
      <el-table-column label="父级菜单" align="center">
        <template slot-scope="{row}">
          <span>{{ row.parentName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center">
        <template slot-scope="{row}">
          <span>{{ row.menuType | authorityMenuType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="权限CODE" align="center">
        <template slot-scope="{row}">
          <span>{{ row.redirect }}</span>
        </template>
      </el-table-column>
      <el-table-column label="权限链接" align="center">
        <template slot-scope="{row}">
          <span>{{ row.url }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{row}">
          <span>{{ row.status === 0 ? '禁用' : '启用' }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="160px">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleDel(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog
      :title="dialogType"
      :visible.sync="dialogVisible"
      width="700px"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="功能图标">
          <el-upload
            action="#"
            list-type="picture-card"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :auto-upload="false"
            :class="{hide:hideUpload}"
            :file-list="imgsList"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
        <el-form-item label="功能名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入功能名称" clearable />
        </el-form-item>
        <el-form-item label="所属系统" prop="systemType">
          <el-select v-model="form.systemType" placeholder="请选择系统" clearable class="filter-item" style="width: 140px" @change="changeSystem">
            <el-option v-for="item in g.systemList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="父级菜单" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择父级菜单" clearable class="filter-item" style="width: 180px">
            <el-option v-for="item in allParentMenu" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="menuType">
          <el-select v-model="form.menuType" placeholder="请选择类型" clearable class="filter-item" style="width: 140px">
            <el-option v-for="item in g.authorityMenuTypeList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限code" prop="perms">
          <el-input v-model="form.perms" placeholder="请输入权限code" clearable />
        </el-form-item>
        <el-form-item label="URL" prop="url">
          <el-input v-model="form.url" placeholder="请输入URL" clearable />
        </el-form-item>
        <el-form-item label="排序" prop="sortNo">
          <el-input v-model="form.sortNo" placeholder="请输入排序" clearable />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择" clearable class="filter-item" style="width: 140px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>

import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import * as Authority from '@/api/system'

export default {
  name: 'AuthorityList',
  directives: { waves },
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
        pageSize: 10,
        orgId: 0,
        menuName: '',
        systemType: '2'
      },

      rules: {
        name: [{ required: true, trigger: 'blur', validator: this.g.checkInputIsEmpty }],
        parentId: [{ required: true, message: '请选择父级菜单', trigger: 'change' }],
        menuType: [{ required: true, message: '请选择类型', trigger: 'change' }],
        perms: [{ required: true, trigger: 'blur', validator: this.g.checkInputIsEmpty }],
        systemType: [{ required: true, message: '请选择系统', trigger: 'change' }],
        url: [{ required: true, trigger: 'blur', validator: this.g.checkInputIsEmpty }],
        sortNo: [{ required: true, trigger: 'blur', validator: this.g.checkInputIsEmpty }]
      },
      allParentMenu: [],
      form: {
        id: '',
        icon: '',
        name: '',
        parentId: '-1',
        menuType: '1',
        perms: '',
        systemType: '2',
        url: '',
        sortNo: '',
        status: 1
      },
      imgsList: [],
      hideUpload: false,
      imgFile: null,

      dialogVisible: false,
      dialogType: ''
    }
  },
  created() {
  },
  mounted() {
    this.getList()
  },
  methods: {
    resetData() {
      this.form.id = ''
      this.form.icon = ''
      this.form.name = ''
      this.form.parentId = '-1'
      this.form.menuType = '1'
      this.form.perms = ''
      this.form.systemType = '2'
      this.form.url = ''
      this.form.sortNo = ''
      this.form.status = 1

      this.imgsList = []
      this.hideUpload = false
      this.imgFile = null
    },
    getList() {
      this.listLoading = true
      Authority.organizeAuthorityList(this.listQuery).then(response => {
        console.log(response.data)
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.currentPage = 1
      this.getList()
    },
    handleUpdate(row) {
      console.log(row)

      this.dialogType = '权限编辑'
      this.dialogVisible = true

      this.getDetail(row)
    },
    getDetail(row) {
      Authority.organizeAuthorityDetail({
        id: row['id']
      }).then(response => {
        const data = response.data
        this.form.id = data.id
        if (data.icon !== null && data.icon !== '') {
          this.imgsList = [
            { url: data.icon }
          ]
          this.hideUpload = true
        }
        this.form.icon = data.icon
        this.form.name = data.name
        this.form.parentId = data.parentId === null ? '-1' : data.parentId.toString()
        this.form.menuType = data.menuType === null ? '' : data.menuType.toString()
        this.form.perms = data.perms
        this.form.systemType = data.systemType === null ? '' : data.systemType.toString()
        this.form.url = data.url
        this.form.sortNo = data.sortNo
        this.form.status = data.status

        this.getOrganizeAuthorityAllMenu()
        console.log(data)
      })
    },
    handleAdd() {
      this.dialogType = '权限新增'
      this.dialogVisible = true

      this.resetData()
      // 所有菜单
      this.getOrganizeAuthorityAllMenu()
    },
    getOrganizeAuthorityAllMenu() {
      Authority.organizeAuthorityAllMenu({
        systemType: this.form.systemType
      }).then(response => {
        this.allParentMenu = response.data
        this.allParentMenu.unshift({
          id: '-1',
          name: '无'
        })
        console.log(this.form.parentId)
      })
    },
    changeSystem(event) {
      console.log(event)
      this.form.systemType = event
      this.getOrganizeAuthorityAllMenu()
      this.form.parentId = ''
    },
    submit() {
      console.log(this.form)

      if (this.imgFile === null && this.form.avatar === null) {
        this.$message({ message: '请选择图片', type: 'error' })
        return
      }

      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.status = this.form.status ? '1' : '0'

          if (this.dialogType === '权限编辑') {
            if (this.imgFile !== null) {
              this.uploadImgToOss(this.imgFile).then(response => {
                console.log('图片上传结果：' + JSON.stringify(response))
                this.form.icon = response
                this.goToEdit()
              })
            } else {
              this.goToEdit()
            }
          } else {
            if (this.imgFile !== null) {
              this.uploadImgToOss(this.imgFile).then(response => {
                console.log('图片上传结果：' + JSON.stringify(response))
                this.form.icon = response
                this.goToAdd()
              })
            } else {
              this.goToAdd()
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    goToAdd() {
      const data = {}
      for (const item of Object.keys(this.form)) {
        data[item] = this.form[item]
      }
      delete data['id']
      data['parentId'] = data['parentId'] === '-1' ? '' : data['parentId']

      Authority.organizeAuthorityAdd(data).then(response => {
        console.log(response)
        this.$message({ message: '提交成功', type: 'success' })
        this.dialogVisible = false
        this.getList()

        this.resetData()
      })
    },
    goToEdit() {
      const data = {}
      for (const item of Object.keys(this.form)) {
        data[item] = this.form[item]
      }
      data['parentId'] = data['parentId'] === '-1' ? '' : data['parentId']

      Authority.organizeAuthorityEdit(data).then(response => {
        console.log(response)
        this.$message({ message: '修改成功', type: 'success' })
        this.dialogVisible = false
        this.getList()

        this.resetData()
      })
    },
    handleDel(row, index) {
      console.log(row)

      this.$confirm('是否确认删除该权限？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(JSON.stringify(this.multipleSelection))
        Authority.organizeAuthorityDel({
          id: row['id']
        }).then(response => {
          this.$message({ message: '操作成功', type: 'success' })
          this.getList()
        })
      })
    },
    handleRemove(file, fileList) {
      console.log('handleChange')
      console.log(file)
      this.hideUpload = false
    },
    handleChange(file, fileList) {
      console.log('handleChange' + fileList.length)
      console.log(file)
      this.imgFile = fileList.length > 0 ? file : null
      this.hideUpload = fileList.length >= 1
    }
  }
}
</script>
<style lang="scss" scoped>
.el-form-item__label {
  font-weight: 400;
}
.hide /deep/.el-upload--picture-card {
	display: none;
  width: 100px;
  height: 100px;
}
/deep/.el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 110px;
}
/deep/.el-upload-list--picture-card /deep/.el-upload-list__item {
  width: 100px;
  height: 100px;
}
</style>
